﻿using Dapper;
using Finance.API.Read.Application.Command.FinancialBookkeepingCommand;
using Finance.Domain;
using Finance.Dtos;
using Finance.ErrorCode;
using Finance.Infrastructrue.Implement;
using MediatR;
using System.Text;

namespace Finance.API.Read.Application.Hander.FinancialBookkeepingHander
{
    public class ShowFinancialBookkeepingHander:IRequestHandler<ShowFinancialBookkeepingCommand,APIResult<FinancialBookkeepingDto>>
    {
        DatabaseContext db;
        ILogger<ShowFinancialBookkeepingHander> logger;

        public ShowFinancialBookkeepingHander(DatabaseContext db, ILogger<ShowFinancialBookkeepingHander> logger)
        {
            this.db = db;
            this.logger = logger;
        }

        public async Task<APIResult<FinancialBookkeepingDto>> Handle(ShowFinancialBookkeepingCommand request, CancellationToken cancellationToken)
        {
           APIPaging <FinancialBookkeepingDto> result=new APIPaging<FinancialBookkeepingDto> ();
            StringBuilder sb=new StringBuilder ();
            StringBuilder page=new StringBuilder ();
            try
            {
                sb.Append(@"SELECT
                               a.FinancialBookkeepingId,
                               a.FlowingWaterNumber,
                               a.FinancialBookkeepingName,
                               a.FinancialBookkeepingType,
                               a.BeneficiaryOrPayer,
                               a.Type,
                               a.PaymentAmount,
                               a.PaymentStype,
                               a.PaymentTime,
                               a.PaymentInstitutions,
                               b.CategoryName
                            FROM financialBookkeeping AS a
                            JOIN financialCategory AS b ON a.FinancialBookkeepingType=b.FinancialCategoryId
                            WHERE a.IsDel=FALSE");
                page.Append(@"SELECT
                              COUNT(a.FinancialBookkeepingId)
                            FROM financialBookkeeping AS a
                            JOIN financialCategory AS b ON a.FinancialBookkeepingType=b.FinancialCategoryId
                            WHERE a.IsDel=FALSE");

                if (!string.IsNullOrEmpty(request.FinancialBookkeepingName))
                {
                    sb.Append(" AND a.FinancialBookkeepingName LIKE @FinancialBookkeepingName");
                    page.Append(" AND a.FinancialBookkeepingName LIKE @FinancialBookkeepingName");
                }

                if (request.FinancialBookkeepingType.HasValue)
                {
                    sb.Append(" AND a.FinancialBookkeepingType = @FinancialBookkeepingType");
                    page.Append(" AND a.FinancialBookkeepingType = @FinancialBookkeepingType");
                }

               

                if (request.STime != null && request.ETime != null)
                {
                    sb.Append(" AND a.CreatTime BETWEEN @STime AND @ETime");
                    page.Append(" AND a.CreatTime BETWEEN @STime AND @ETime");
                }

                

                sb.Append(" ORDER BY a.FinancialBookkeepingId DESC LIMIT @PageSize OFFSET @offset");
                var parameters = new
                {
                    FinancialBookkeepingName = $"%{request.FinancialBookkeepingName}%",
                    request.FinancialBookkeepingType,
                    STime = request.STime,
                    ETime = request.ETime,
                    offset = (request.PageIndex - 1) * request.PageSize,
                    request.PageSize
                };

                var pageData = await db.DapperConnection.QueryAsync<FinancialBookkeepingDto>(sb.ToString(), parameters);
                int totalCount = await db.DapperConnection.ExecuteScalarAsync<int>(page.ToString(), parameters);
                int totalPage = (int)Math.Ceiling(totalCount / (double)request.PageSize);

                result.PageDatas = pageData.ToList();
                result.TotalCount = totalCount;
                result.TotalPage = totalPage;
                result.Message = "应付管理显示成功";
                result.Code = APIEnum.Ok;
                logger.LogInformation("显示成功");
                return result;

            }
            catch (Exception ex)
            {
                logger.LogError("应收管理显示失败" + ex.Message);
                throw;
            }
        }
    }
}
